package com.fjec.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.shiro.AccountInfo;
import com.fjec.common.util.DateUtil;
import com.fjec.market.entity.BizPurchasing;
import com.fjec.market.entity.InfoPurchase;
import com.fjec.market.mapper.BizPurchasingMapper;
import com.fjec.market.service.IBizPurchasingService;
import com.fjec.market.service.IInfoPurchaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * <p>
 * 007.采购商采购需求表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-09-14
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class BizPurchasingServiceImpl extends ServiceImpl<BizPurchasingMapper, BizPurchasing> implements IBizPurchasingService {

    @Resource
    private BizPurchasingMapper mapper;

    @Resource
    private IInfoPurchaseService infoPurchaseService;

    @Override
    public List<BizPurchasing> getPurchasingByUserId(Long userId) {
        return mapper.getPurchasingByUserId(userId);
    }

    @Override
    public JsonResult savePurchasing(BizPurchasing bizPurchasing, Long userId) {
        Long id = infoPurchaseService.getOne(new QueryWrapper<InfoPurchase>().eq("UserId", userId)).getId();
        bizPurchasing.setPurcId(id);
        int validPeriodNum = bizPurchasing.getValidPeriodNum();
        LocalDate validPeriod = DateUtil.ldPlus(DateUtil.nowLd(), ChronoUnit.DAYS, validPeriodNum);
        bizPurchasing.setValidPeriod(validPeriod);
        bizPurchasing.setCreateTime(DateUtil.nowLdt());

        boolean saved = this.save(bizPurchasing);
        if (saved) return JsonResult.SUCCESS;
        else return JsonResult.FAILURE;
    }

    @Override
    public JsonResult getMyPurchasing() {
        return JsonResult.success().data(this.getPurchasingByUserId(AccountInfo.getUserId())).build();
    }

    @Override
    public List<BizPurchasing> get2PurchasingByPurchaseIds(List<Long> purchaseIds) {
        return mapper.get2PurchasingByPurchaseIds(purchaseIds);
    }

    @Override
    public List<BizPurchasing> getPurchasingByPurchaseIds(List<Long> purchaseIds) {
        return mapper.getPurchasingByPurchaseIds(purchaseIds);
    }
}
